package com.tnovoselec.server.travelassistant.worker;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.nio.channels.Channels;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.tnovoselec.server.travelassistant.Config;
import com.tnovoselec.server.travelassistant.beans.Price;
import com.tnovoselec.server.travelassistant.util.Util;
import com.tnovoselec.server.travelassistant.util.XMLUtil;

public class GasPricesParser implements IParser{
	
	private List<Price> prices;
	private Document document = null;

	@Override
	public void parse() {
		parseGasPrices();
		
	}

	@Override
	public Document getDoc() {
		
		return document;
	}

	@Override
	public String getXMLName() {
		return Config.GAS_PRICES_XML_NAME;
	}
	
	private void parseGasPrices() {
		try {
			prices = new ArrayList<Price>();
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode rootNode = cleaner.clean(new URL(Config.gasPricesURL));
			List<TagNode> divs = Util.getDivsByClass(Config.className, rootNode);
			TagNode divElement = (TagNode) divs.get(0);
			TagNode body[] = divElement.getElementsByName("tbody", true);
			TagNode tbody = body[0];
			for (TagNode node : tbody.getElementsByName("tr", true)) {
				String name = node.getElementsByName("td", true)[0].getText().toString();
				String price = node.getElementsByName("td", true)[1].getText().toString();
				Price priceObj = new Price(name, price);
				System.out.println(priceObj);
				prices.add(priceObj);
			}
			buildGasPricesXML();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	private void buildGasPricesXML() {
		try {
			document = XMLUtil.getEmptyDoc();
			Element root = XMLUtil.createElement(document, "root", null);
			for (Price price : prices) {
				Element p = XMLUtil.createElement(document, "prices", root);
				XMLUtil.createElement(document, "name", price.getName(), p);
				XMLUtil.createElement(document, "price", price.getPrice(), p);
			}
			document.appendChild(root);
			document.normalize();

			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
